package com.tkp.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;

import java.io.*;

/**
 * @Author: duk
 * @Date: 2021/11/9 15:10
 * @Description: byte转换操作
 */
public class ByteShiftUtil {

    /**
     * 根据byte[]和文件路径名称生成文件
     * @param bytes byte数据
     * @param filepath 文件名称及其路径
     */
    public static void createFile(byte[] bytes, String filepath) throws Exception {
        //获取输入流
        OutputStream inputStream = FileUtil.getOutputStream(filepath);
        //转换为文件并关闭流
        IoUtil.write(inputStream,true,bytes);
    }

    /**
     * String类型转换byte[]
     * @param hex 要转换的字符串
     * @return byte数组
     */
    public static byte[] hexStringToByte(String hex) {
        int len = (hex.length() / 2);
        byte[] result = new byte[len];
        char[] achar = hex.toCharArray();
        for (int i = 0; i < len; i++) {
            int pos = i * 2;
            result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
        }
        return result;
    }

    private static byte toByte(char c) {
        byte b = (byte) "0123456789abcdef".indexOf(c);
        return b;
    }
}
